package org.huzhp.gateway.filter.balance;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;

import java.util.List;

/**
 * @Description: java类作用描述
 * @Author: huzp
 * @CreateDate: 2020/4/16 14:13
 * @Version: 1.0
 */
public class GatewayLoadBalanceClient {

    private GatewaySpringClientFactory clientFactory;

    public static final String DEFAULT_ZONE_HEADER = "Gateway_Request_Zone";
    public static final String DEFAULT_ZONE = "default";
    public static final String DEFAULT_RULE = "Random";

    public GatewayLoadBalanceClient(GatewaySpringClientFactory clientFactory) {
        this.clientFactory = clientFactory;
    }


    protected ILoadBalancer getLoadBalancer(String rule,String serviceId) {
        return this.clientFactory.getLoadBalancer(rule,serviceId);
    }


    protected Server getServer(ILoadBalancer loadBalancer, Object hint) {
        return loadBalancer == null ? null : loadBalancer.chooseServer(hint==null?DEFAULT_ZONE:hint);
    }

    public ServiceInstance choose(String serviceId,List<Server> servers) {
        return choose(serviceId,servers,DEFAULT_ZONE);
    }

    public ServiceInstance choose(String serviceId,List<Server> servers,String hint) {
        return choose(serviceId,DEFAULT_RULE,servers,hint);
    }


    public ServiceInstance choose(String serviceId,String rule,List<Server> servers,String hint) {
        ILoadBalancer loadBalancer = this.getLoadBalancer(rule,serviceId);
        if (loadBalancer.getAllServers().size()==0) {
            loadBalancer.addServers(servers);
        }
        Server server = this.getServer(loadBalancer, hint);
        return server == null ? null : new RibbonLoadBalancerClient.RibbonServer(serviceId, server);
    }


}
